#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time    : 2020/10/14 11:22 上午
# @Author  : HuiDong.Bai
# @Email   : huidong.bai@ximalaya.com
# @File    : SerialReadSN.py
# @Software: PyCharm

from SerialReader import get_serial_com
import serial
import time
from threading import Thread, currentThread
import datetime


def read_serial():
    com_port = get_serial_com()
    ser = serial.Serial(com_port, '115200', timeout=4)
    cmd = 'sys no\nsys id\nsys app\n'
    ser.write(cmd.encode())

    start_time = datetime.datetime.now()
    t = currentThread()
    with open('info.txt', 'a+', encoding='UTF-8') as fp:
        # while getattr(t, "open", True):
        #     line = ser.readline().decode(encoding='UTF-8').replace('\n', '').strip()
        #     # print(line)
        #     fp.write(line)

        while True:
            end_time = datetime.datetime.now()
            line = ser.readline().strip()
            log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")
            fp.write(log)
            if (end_time - start_time).seconds == 1:
                break


if __name__ == '__main__':
    t = Thread(target=read_serial)
    t.start()
    time.sleep(2)
    with open('./info.txt', 'r', encoding='UTF-8') as f:
        text = f.readline()

    for i in text.split('>'):
        if 'sys id' in i:
            print(i.split('sys id')[1])
        elif 'sys app' in i:
            print(i.split('sys app')[1])

